package com.autonavi.yunda.yunji.core.utils.diling;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author cizhong.wcs
 * @date 2023/4/27 10:30
 */
public class GenerateTokenCoreUtils {

    private static final int MD5_LEN = 16;
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static final MessageDigest DIGESTER;

    static {
        try {
            DIGESTER = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    //检查token
    public static String getGenerateMD5Token(String doString) {
        try {
            if (doString != null) {
                byte[] digest;
                synchronized (DIGESTER) {
                    DIGESTER.update(doString.getBytes("UTF-8"));
                    digest = DIGESTER.digest();
                }
                return getGenerateMD5Token(digest);
            }
        } catch (Exception e) {
        }
        return null;
    }

    private static String getGenerateMD5Token(byte[] digest) {
        StringBuffer buf = new StringBuffer(MD5_LEN * 2);
        for (int i = 0; i < MD5_LEN; i++) {
            int b = digest[i];
            buf.append(HEX_DIGITS[(b >> 4) & 0xf]);
            buf.append(HEX_DIGITS[b & 0xf]);
        }
        return buf.toString();
    }

}
